package com.ruoyi.web.service.custom.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gitee.deeround.jdbchelper.DbAction;
import com.ruoyi.core.entity.BaseMap;
import com.ruoyi.core.util.IdUtil;
import com.ruoyi.flow.listener.FlowListenerContainer;
import com.ruoyi.flow.service.FlowMachineService;
import com.ruoyi.web.domain.SysMod;
import com.ruoyi.web.domain.SysModColumn;
import com.ruoyi.web.exception.ApiException;
import com.ruoyi.web.listener.DefaultFlowListener;
import com.ruoyi.web.service.SysModColumnService;
import com.ruoyi.web.service.SysModDbService;
import com.ruoyi.web.service.custom.SysModModDataService;
import com.ruoyi.web.service.impl.SysModDataServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysModModDataServiceImpl extends SysModDataServiceImpl implements SysModModDataService {

    @Autowired
    private SysModColumnService sysModColumnService;

    @Autowired
    private SysModDbService sysModDbService;

    @Autowired
    private FlowMachineService flowMachineService;

    @Autowired
    private DbAction dbAction;

    @Override
    public BaseMap add(String modId, BaseMap entity) {

        entity.put("mod_id", IdUtil.sequenceId());
        if (entity.getBoolean("is_flow", false)) {
            entity.put("machine_id", entity.getString("mod_id"));

            //如果流程不存在则创建流程模板
            if (dbAction.queryForInteger("select count(1) cnt from flow_machine where machine_id=?", entity.getString("machine_id")) == 0) {
                String machineJson = "{\"id\":\"{modId}\",\"name\":\"{modName}\",\"states\":[],\"events\":[{\"id\":\"add\",\"name\":\"新增\",\"type\":\"OTHER\",\"rejectType\":null,\"rejectNode\":null,\"operate\":\"ADD\",\"color\":\"primary\",\"icon\":\"Plus\",\"seq\":1,\"selected\":\"0\"},{\"id\":\"edit\",\"name\":\"修改\",\"type\":\"OPERATE\",\"rejectType\":null,\"rejectNode\":null,\"operate\":\"EDIT\",\"color\":\"primary\",\"icon\":\"Edit\",\"seq\":2,\"selected\":\"1\"},{\"id\":\"delete\",\"name\":\"删除\",\"type\":\"OPERATE\",\"rejectType\":null,\"rejectNode\":null,\"operate\":\"DELETE\",\"color\":\"danger\",\"icon\":\"Delete\",\"seq\":3,\"selected\":\"1\"},{\"id\":\"view\",\"name\":\"查看\",\"type\":\"OTHER\",\"operate\":\"VIEW\",\"color\":\"primary\",\"icon\":\"View\",\"selected\":\"1\",\"seq\":\"4\"}],\"conditions\":[],\"nodes\":[{\"left\":\"150\",\"top\":\"120\",\"id\":\"node_{modId}1\",\"name\":\"开始\",\"type\":null,\"state\":\"\",\"handlers\":[],\"back\":\"0\"},{\"left\":\"440\",\"top\":\"120\",\"id\":\"node_{modId}2\",\"name\":\"结束\",\"type\":null,\"state\":\"\",\"handlers\":[],\"back\":\"0\"}],\"lines\":[{\"source\":\"node_{modId}1\",\"target\":\"node_{modId}2\",\"id\":\"line_{modId}1\",\"when\":\"\",\"on\":\"\",\"handlers\":[],\"seq\":99},{\"source\":\"node_{modId}1\",\"target\":\"node_{modId}1\",\"id\":\"line_{modId}2\",\"when\":\"\",\"on\":\"edit\",\"handlers\":[],\"seq\":99},{\"source\":\"node_{modId}1\",\"target\":\"node_{modId}1\",\"id\":\"line_{modId}3\",\"when\":\"\",\"on\":\"delete\",\"handlers\":[],\"seq\":99}]}";
                machineJson = machineJson.replace("{modId}", entity.getString("machine_id")).replace("{modName}", entity.getString("mod_name"));
                flowMachineService.publish(machineJson);
                //注册默认监听
                FlowListenerContainer.register(entity.getString("machine_id"), new DefaultFlowListener());
            }
        }

        entity.put("table_name", entity.getString("table_name").toLowerCase());
        entity.put("primary_key", entity.getString("primary_key").toLowerCase());

        super.add(modId, entity);

        //添加固定列：主键、流程列、创建人、创建时间、更新人、更新时间等
        SysModColumn column1 = new SysModColumn();
        column1.setColumnId(IdUtil.sequenceId());
        column1.setColumnName(entity.getString("primary_key"));
        column1.setColumnLabel("ID");
        column1.setControlType("input");
        column1.setControlOrderNum(99);
        column1.setControlWidth(12);
        column1.setDataLength(32);
        column1.setDataScale(0);
        column1.setDataSourceType("none");
        column1.setDataType("String");
        column1.setIsAllowNull("0");
        column1.setIsDefaultSortColumn("0");
        column1.setIsEditReadonly("0");
        column1.setIsHide("1");
        column1.setIsListColumn("0");
        column1.setIsMultiple("0");
        column1.setIsPrimaryKey("1");
        column1.setIsQueryLeft("0");
        column1.setIsQueryMultiple("0");
        column1.setIsReadonly("0");
        column1.setIsRequired("0");
        column1.setIsSortColumn("0");
        column1.setIsSystemColumn("1");
        column1.setListColumnOrderNum(99);
        column1.setListColumnWidth(0);
        column1.setModId(entity.getString("mod_id"));
        column1.setQueryOrderNum(99);
        column1.setQueryType("none");
        column1.setSumType("none");
        sysModColumnService.save(column1);


        sysModDbService.createTable(getModInfo(entity.getString("mod_id")));

        return getById(modId, entity);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public BaseMap edit(String modId, BaseMap entity) {
        entity.put("table_name", entity.getString("table_name").toLowerCase());
        entity.put("primary_key", entity.getString("primary_key").toLowerCase());
        if (entity.getBoolean("is_flow", false)) {
            entity.put("machine_id", entity.getString("mod_id"));

            //如果流程不存在则创建流程模板
            if (dbAction.queryForInteger("select count(1) cnt from flow_machine where machine_id=?", entity.getString("machine_id")) == 0) {
                String machineJson = "{\"id\":\"{modId}\",\"name\":\"{modName}\",\"states\":[],\"events\":[{\"id\":\"add\",\"name\":\"新增\",\"type\":\"OTHER\",\"rejectType\":null,\"rejectNode\":null,\"operate\":\"ADD\",\"color\":\"primary\",\"icon\":\"Plus\",\"seq\":1,\"selected\":\"0\"},{\"id\":\"edit\",\"name\":\"修改\",\"type\":\"OPERATE\",\"rejectType\":null,\"rejectNode\":null,\"operate\":\"EDIT\",\"color\":\"primary\",\"icon\":\"Edit\",\"seq\":2,\"selected\":\"1\"},{\"id\":\"delete\",\"name\":\"删除\",\"type\":\"OPERATE\",\"rejectType\":null,\"rejectNode\":null,\"operate\":\"DELETE\",\"color\":\"danger\",\"icon\":\"Delete\",\"seq\":3,\"selected\":\"1\"},{\"id\":\"view\",\"name\":\"查看\",\"type\":\"OTHER\",\"operate\":\"VIEW\",\"color\":\"primary\",\"icon\":\"View\",\"selected\":\"1\",\"seq\":\"4\"}],\"conditions\":[],\"nodes\":[{\"left\":\"150\",\"top\":\"120\",\"id\":\"node_{modId}1\",\"name\":\"开始\",\"type\":null,\"state\":\"\",\"handlers\":[],\"back\":\"0\"},{\"left\":\"440\",\"top\":\"120\",\"id\":\"node_{modId}2\",\"name\":\"结束\",\"type\":null,\"state\":\"\",\"handlers\":[],\"back\":\"0\"}],\"lines\":[{\"source\":\"node_{modId}1\",\"target\":\"node_{modId}2\",\"id\":\"line_{modId}1\",\"when\":\"\",\"on\":\"\",\"handlers\":[],\"seq\":99},{\"source\":\"node_{modId}1\",\"target\":\"node_{modId}1\",\"id\":\"line_{modId}2\",\"when\":\"\",\"on\":\"edit\",\"handlers\":[],\"seq\":99},{\"source\":\"node_{modId}1\",\"target\":\"node_{modId}1\",\"id\":\"line_{modId}3\",\"when\":\"\",\"on\":\"delete\",\"handlers\":[],\"seq\":99}]}";
                machineJson = machineJson.replace("{modId}", entity.getString("machine_id")).replace("{modName}", entity.getString("mod_name"));
                flowMachineService.publish(machineJson);
                //注册默认监听
                FlowListenerContainer.register(entity.getString("machine_id"), new DefaultFlowListener());
            }
        }

        SysMod mod = getMod(entity.getString("mod_id"));
        //主键不允许修改
        if (!mod.getPrimaryKey().equals(entity.getString("primary_key"))) {
            throw new ApiException("主键不允许修改");
        }
        //判断表名是否修改
        if (!mod.getTableName().equals(entity.getString("table_name"))) {
            throw new ApiException("物理表名不允许修改");
        }
        return super.edit(modId, entity);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void delete(String modId, BaseMap entity) {


        SysMod mod = getMod(entity.getString("mod_id"));

        if ("17005103583592448".equals(mod.getGroupId())) {
            throw new ApiException("系统管理模块不能删除");
        }

        super.delete(modId, entity);

        sysModColumnService.remove(Wrappers.<SysModColumn>query().lambda().eq(SysModColumn::getModId, entity.getString("mod_id")));

        sysModDbService.deleteTable(mod);

    }

}
